<template>
  <div class='map'>
  </div>
</template>
<script>
import mixins from '@/utils/mixins';
import wx from 'weixin-js-sdk';
export default {
  name: 'storemap',
  data () {
    return {
      map_info: {}
    };
  },
  mixins: [mixins],
  created () {
    this.init();
  },
  methods: {
    init() {
      let that = this;
      that.map_info = JSON.parse(localStorage.getItem('map_info'));
      let code = that.$route.query.code; // 获取url参数code
      if (code) {
        that.getOpenId(code);
      } else {
        that.wxGetCode('');
      }
    },
    wxGetCode(state) {
      let that = this;
      let APPID = that.map_info.appid;
      let SCOPE = 'snsapi_base';
      let REDIRECT_URI = that.$WEB_URL + '/store/map'; // that.$WEB_URL+
      let pin_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + REDIRECT_URI + '&response_type=code&scope=' + SCOPE + '&state=' + state + '#wechat_redirect';
      window.location.href = pin_url;
    },
    getOpenId(code) { // 获得openId
      var that = this;
      var options = {};
      options.url = location.href.split('#')[0];
      options.code = code;
      that.$API.home.getOpenIdApi(options).then(res => {
        if (res.code !== 0) {
          that.wxGetCode('');
          return;
        }
        console.log(res);
        let data = res.data;
        that.openId = data.openid;
        wx.config({
          debug: false, // 这里一般在测试阶段先用true，等打包给后台的时候就改回false,
          appId: data.js_appid,
          timestamp: data.js_timestamp,
          nonceStr: data.js_nonceStr,
          signature: data.js_signature,
          jsApiList: ['openLocation']
        });
        wx.ready(function() {
          wx.checkJsApi({
            jsApiList: ['openLocation'],
            success: function(res) {
              console.log('success');
              that.getMap();
            },
            fail: function(res) {
              console.log('fail');
              console.log(res);
            }
          });
        });
      });
    },
    getMap() {
      var that = this;
      wx.ready(function() {
        wx.openLocation({
          latitude: that.map_info.lat,
          longitude: that.map_info.lng,
          name: that.map_info.shop_name,
          address: that.map_info.address,
          scale: 14,
          infoUrl: 'http://weixin.qq.com'
        });
      });
    }
  }
};
</script>
<style lang="less" rel="stylesheet/less" scoped>
  .map {
    width:100vw;
    height:100vh;
  }
</style>
